
package com.hlkj.pay.app.merchant.ext.impl.hnapay.utils;

import cn.hutool.json.JSONObject;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.pay.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by Ricky on 2016/11/20.
 */
@Slf4j
public class HttpUtils {

    /**
     * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
     */
    public static String post(String url, Object jsonObject) {
        return post(url, JsonUtils.toJsonString(jsonObject));
    }
    public static String post(String url, JSONObject jsonObject) {
        return post(url, jsonObject.toString());
    }
    public static String post(String url, Map<String, String> params) {
        return post(url, JsonUtils.toJsonString(params));
    }

    public static String post(String url, String json) {
        StringBuilder result = new StringBuilder();

        // 创建默认的httpClient实例.
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建HttpPost对象
            HttpPost httpPost = new HttpPost(url);
            StringEntity reqEntity = new StringEntity(json, "UTF-8");

            // 设置POST请求的实体
            httpPost.setEntity(reqEntity);
            httpPost.setHeader("Content-Type", "application/json");
            // 执行请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result.append(EntityUtils.toString(entity));
                }
            }
            log.info("新生支付返回参数 url:{}, params:{}, response:{}", httpPost.getURI(), json, result);
            return result.toString();
        } catch (IOException e) {
            log.error("请求失败，url: {}, params: {}", url, json, e);
        }
        return null;
    }

    /**
     * 发送 get请求访问本地应用并根据传递参数不同返回不同结果
     */
    public static String get(String url, JSONObject jsonObject) {
        StringBuilder result = new StringBuilder();
        // 创建默认的httpClient实例.
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            String queryString = convertJSONToQueryParams(jsonObject);
            HttpGet httpGet = new HttpGet(url + "?" + queryString);

            // 执行请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result.append(EntityUtils.toString(entity));
                }
            }
            log.info("新生支付返回参数 url:{}, response:{}", httpGet.getURI(), result);
            return result.toString();
        } catch (IOException e) {
            log.error("请求失败，url: {}", url, e);
        }
        return null;
    }

    public static String convertJSONToQueryParams(JSONObject jsonObject) throws UnsupportedEncodingException {
        StringBuilder queryParams = new StringBuilder();

        // 遍历JSONObject的所有键
        for (String key : jsonObject.keySet()) {
            Object value = jsonObject.get(key);
            if (value != null) {
                if (queryParams.length() > 0) {
                    queryParams.append("&");
                }
                // 使用URLEncoder来确保参数值是经过正确编码的
                queryParams.append(URLEncoder.encode(key, "UTF-8"))
                        .append("=")
                        .append(URLEncoder.encode(value.toString(), "UTF-8"));
            }
        }

        return queryParams.toString();
    }

    private static String getRequestParamString(Map<String, String> requestParam) throws UnsupportedEncodingException {
        String charset = "UTF-8";
        StringBuilder sb = new StringBuilder();

        for (Map.Entry<String, String> entry : requestParam.entrySet()) {
            if (entry.getValue() == null) {
                continue;
            }
            sb.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), charset)).append("&");
        }
        String s_ret = sb.toString();
        if (s_ret.isEmpty()) {
            return "";
        }
        s_ret = s_ret.substring(0, s_ret.length() - 1);
        return s_ret;
    }

    /**
     * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
     */
    public static String postForm(String url, Map<String, String> map) {
        StringBuilder result = new StringBuilder();
        // 创建默认的httpClient实例.
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建HttpPost对象
            HttpPost httpPost = new HttpPost(url);
            StringEntity reqEntity = new StringEntity(getRequestParamString(map), "UTF-8");

            // 设置POST请求的实体
            httpPost.setEntity(reqEntity);
            httpPost.setHeader(HTTP.CONTENT_ENCODING, "UTF-8");
            httpPost.setHeader(HTTP.USER_AGENT, "Rich Powered/1.0");
            httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
            // 执行请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result.append(EntityUtils.toString(entity));
                }
            }
            log.info("新生返回参数 , params:{}, response:{}", JsonUtils.toJsonString(map), result);
            return result.toString();
        } catch (IOException e) {
            log.error("请求失败，url: {}, params: {}", url, map, e);
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
        String imageUrl = "https://gateway.hnapay.com/rpt/rpt02.do";
        String sm2PrivateKey = "70caa9733bd092f125f392c3a2f327c89d94aed8b01f83b2518da181f3205f0b";
        String publicKey = "03420004711FDF628597D554610C0600889F391A53D6232F62F7D579A9071CDCD3049296FD97872FA9B9E0A687C43A2B021E800F385E3CCC56667B811CC93A3DDE57E3CF";
        Map<String, String> bodyMap = new LinkedHashMap<>();
        bodyMap.put("version", "2.0");
        bodyMap.put("tranCode", "RPT02");
        bodyMap.put("merId", "11000011848");
        bodyMap.put("merOrderId", "123123123");
        bodyMap.put("reportedNo", "2506171349394226164");
        bodyMap.put("submitTime", DateUtils.getDateString(net.dreamlu.mica.core.utils.DatePattern.PURE_DATETIME_PATTERN));
        bodyMap.put("signValue", RecepitUtil.sign(sm2PrivateKey, bodyMap));
        bodyMap.put("signType", "3");
        bodyMap.put("charset", "1");

        String rsp = HttpUtils.postForm(imageUrl, bodyMap);
        System.out.println(rsp);

    }

}
